package pl.edu.pw.ee.buildcity.notifiers;

import org.fest.assertions.Assertions;
import org.fest.assertions.Fail;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import pl.edu.pw.ee.buildcity.domain.BuildStatus;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.entities.BuildDefinition;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author Mateusz
 * @since 2010-02-14
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:gg-notifier-context.xml", "classpath:test-context.xml"})
public class GGNotifierIntegrationTestCase {

	@Resource(name = "ggNotifier")
	private GGNotifier notifier;

	@Test
	public void shouldNotifyEndOfBuild() {
		//Given
		BuildDefinition buildDefinition = new BuildDefinition().withName("My Build");

		BuildActivity buildActivity = new BuildActivity().ended(new Date());
		buildActivity.setResult(BuildStatus.FAILED);
		buildActivity.setBuildDefinition(buildDefinition);
		buildActivity.setBuildNumber(new Random().nextInt(100));

		List<String> recipients = Arrays.asList("1002098");

		//When
		notifier.notifyEndOfBuild(recipients, buildActivity);
		sleep(10);

		//Then
		//See at your GG client ;)
	}

	@Test
	public void shouldThrowExceptionWhenCouldNotNotify() {
		//Given
		BuildDefinition buildDefinition = new BuildDefinition().withName("My Build");

		BuildActivity buildActivity = new BuildActivity().ended(new Date());

		List<String> recipients = Arrays.asList("wrongNonIntegerUIN");

		//When
		try {
			notifier.notifyEndOfBuild(recipients, buildActivity);
			Fail.fail("Exception should be throws as UIN is invalid and GG msg couldn't be sent");
		} catch (Exception e) {
			//Then
			Assertions.assertThat(e).isInstanceOf(CouldNotNotifyException.class);
			Assertions.assertThat(e.getMessage()).startsWith("Could not send message to recipient 'wrongNonIntegerUIN' due to exception:");
		}
	}


	private void sleep(int seconds) {
		try {
			Thread.sleep(seconds * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
